<script setup lang="ts">
import type { BaseEnum } from '@/enums/base'
import { computed, ref, watch } from 'vue'

interface Props {
  // 枚举对象或枚举数组
  enumData: Record<string, BaseEnum>
  // 选择器类型：select-下拉框，radio-单选按钮，tab-标签风格，mobile-移动端优化
  type?: 'select' | 'radio' | 'tab' | 'mobile'
  // 是否多选
  multiple?: boolean
  // 默认值
  modelValue?: any
  // 禁用的值
  disabledValues?: (string | number)[]
  // 占位符
  placeholder?: string
  // 尺寸
  size?: 'large' | 'default' | 'small'
  // 是否禁用
  disabled?: boolean
  // 是否显示搜索框
  searchable?: boolean
}

const props = withDefaults(defineProps<Props>(), {
  type: 'mobile',
  multiple: false,
  modelValue: '',
  disabledValues: () => [],
  placeholder: '请选择',
  size: 'default',
  disabled: false,
  searchable: false,
})

const emit = defineEmits(['update:modelValue', 'change'])

// 响应式状态
const selectedValue = ref<any>(props.modelValue || '')
const showMobilePicker = ref(false)
const searchText = ref('')

// 计算属性
const options = computed(() => {
  const baseOptions = Object.values(props.enumData)

  // 搜索过滤
  if (props.searchable && searchText.value) {
    return baseOptions.filter((item) =>
      item.name.toLowerCase().includes(searchText.value.toLowerCase()),
    )
  }

  return baseOptions
})

const displayText = computed(() => {
  if (props.multiple && Array.isArray(selectedValue.value)) {
    const selectedItems = options.value.filter((item) => selectedValue.value.includes(item.code))
    return selectedItems.map((item) => item.name).join(', ')
  } else {
    const selectedItem = options.value.find((item) => item.code === selectedValue.value)
    return selectedItem?.name || ''
  }
})

const sizeClass = computed(() => {
  const sizeMap = {
    small: 'enum-select--small',
    default: 'enum-select--default',
    large: 'enum-select--large',
  }
  return sizeMap[props.size]
})

// 工具函数
function isDisabled(code: string | number): boolean {
  return props.disabled || props.disabledValues.includes(code)
}

function isItemSelected(code: string | number): boolean {
  if (props.multiple && Array.isArray(selectedValue.value)) {
    return selectedValue.value.includes(code)
  }
  return selectedValue.value === code
}

// 事件处理
function handlePickerConfirm(value: any) {
  const selectedCode = value[0]
  selectedValue.value = selectedCode
  handleChange(selectedCode)
}

function handleMobileSelect(code: string | number) {
  if (props.multiple && Array.isArray(selectedValue.value)) {
    const newValue = [...selectedValue.value]
    const index = newValue.indexOf(code)

    if (index > -1) {
      newValue.splice(index, 1)
    } else {
      newValue.push(code)
    }

    selectedValue.value = newValue
    handleChange(newValue)
  } else {
    selectedValue.value = code
    handleChange(code)
    showMobilePicker.value = false
  }
}

function handleTabClick(code: string | number) {
  if (isDisabled(code)) return

  if (props.multiple && Array.isArray(selectedValue.value)) {
    const newValue = [...selectedValue.value]
    const index = newValue.indexOf(code)

    if (index > -1) {
      newValue.splice(index, 1)
    } else {
      newValue.push(code)
    }

    selectedValue.value = newValue
    handleChange(newValue)
  } else {
    selectedValue.value = code
    handleChange(code)
  }
}

function handleChange(val: any) {
  emit('update:modelValue', val)
  const selectedEnum = props.multiple
    ? options.value.filter((item) => val.includes(item.code))
    : options.value.find((item) => item.code === val)
  emit('change', selectedEnum)
}

function handleSearchInput(event: any) {
  searchText.value = event.detail.value
}

function clearSearch() {
  searchText.value = ''
}

// 监听器
watch(
  () => props.modelValue,
  (newVal) => {
    selectedValue.value = newVal || ''
  },
)
</script>

<template>
  <view class="enum-select" :class="[sizeClass, { 'enum-select--disabled': disabled }]">
    <!-- 下拉框模式 -->
    <wd-picker
      v-if="type === 'select'"
      v-model="selectedValue"
      :columns="[options]"
      :placeholder="placeholder"
      :disabled="disabled"
      @confirm="handlePickerConfirm"
    >
      <wd-cell :title="displayText" :value="displayText" />
    </wd-picker>

    <!-- 单选按钮模式 -->
    <wd-radio-group
      v-else-if="type === 'radio'"
      v-model="selectedValue"
      :disabled="disabled"
      class="enum-radio-group"
      @change="handleChange"
    >
      <wd-radio
        v-for="item in options"
        :key="item.code"
        :value="item.code"
        :disabled="isDisabled(item.code)"
        class="enum-radio-item"
      >
        <view class="radio-content">
          <text class="radio-label">
            {{ item.name }}
          </text>
          <text v-if="item.tooltip" class="radio-tooltip">
            {{ item.tooltip }}
          </text>
        </view>
      </wd-radio>
    </wd-radio-group>

    <!-- Tab风格模式 -->
    <view v-else-if="type === 'tab'" class="enum-tabs">
      <view
        v-for="item in options"
        :key="item.code"
        class="enum-tab-item"
        :class="{
          'enum-tab-item--active': isItemSelected(item.code),
          'enum-tab-item--disabled': isDisabled(item.code),
        }"
        @click="!isDisabled(item.code) && handleTabClick(item.code)"
      >
        <text class="tab-label">
          {{ item.name }}
        </text>
        <wd-tooltip v-if="item.tooltip" :content="item.tooltip" placement="top">
          <wd-icon name="info" size="12" class="tab-info-icon" />
        </wd-tooltip>
      </view>
    </view>

    <!-- 移动端优化的选择器模式 -->
    <view v-else-if="type === 'mobile'" class="enum-mobile">
      <view
        class="mobile-trigger"
        :class="{ 'mobile-trigger--active': showMobilePicker }"
        @click="!disabled && (showMobilePicker = true)"
      >
        <text class="mobile-label" :class="{ 'mobile-label--placeholder': !displayText }">
          {{ displayText || placeholder }}
        </text>
        <wd-icon
          name="arrow-down"
          size="16"
          class="mobile-arrow"
          :class="{ 'mobile-arrow--active': showMobilePicker }"
        />
      </view>

      <!-- 移动端选择弹窗 -->
      <wd-popup
        v-model="showMobilePicker"
        position="bottom"
        class="mobile-picker-popup"
        :safe-area-inset-bottom="true"
      >
        <view class="picker-container">
          <!-- 头部 -->
          <view class="picker-header">
            <view class="picker-header-content">
              <text class="picker-title">请选择</text>
              <wd-button
                type="primary"
                size="small"
                class="picker-done-btn"
                @click="showMobilePicker = false"
              >
                完成
              </wd-button>
            </view>
          </view>

          <!-- 搜索框 -->
          <view v-if="searchable" class="picker-search">
            <view class="search-input-wrapper">
              <wd-icon name="search" size="16" class="search-icon" />
              <input
                v-model="searchText"
                class="search-input"
                placeholder="搜索选项..."
                @input="handleSearchInput"
              />
              <wd-icon
                v-if="searchText"
                name="close"
                size="16"
                class="search-clear"
                @click="clearSearch"
              />
            </view>
          </view>

          <!-- 选项列表 -->
          <scroll-view class="picker-content" scroll-y>
            <view
              v-for="item in options"
              :key="item.code"
              class="picker-item"
              :class="{
                'picker-item--selected': isItemSelected(item.code),
                'picker-item--disabled': isDisabled(item.code),
              }"
              @click="!isDisabled(item.code) && handleMobileSelect(item.code)"
            >
              <view class="picker-item-content">
                <text class="picker-item-text">
                  {{ item.name }}
                </text>
                <text v-if="item.tooltip" class="picker-item-tooltip">
                  {{ item.tooltip }}
                </text>
              </view>
              <wd-icon
                v-if="isItemSelected(item.code)"
                name="check"
                size="16"
                class="picker-item-check"
              />
            </view>

            <!-- 空状态 -->
            <view v-if="options.length === 0" class="picker-empty">
              <wd-icon name="search" size="48" class="empty-icon" />
              <text class="empty-text">暂无匹配选项</text>
            </view>
          </scroll-view>
        </view>
      </wd-popup>
    </view>
  </view>
</template>

<style scoped lang="scss">
// Apple 设计系统变量
:root {
  --apple-blue: #007aff;
  --apple-blue-light: #5ac8fa;
  --apple-blue-dark: #0056cc;
  --apple-gray: #8e8e93;
  --apple-gray-light: #c7c7cc;
  --apple-gray-dark: #48484a;
  --apple-red: #ff3b30;
  --apple-green: #34c759;
  --apple-background: #f2f2f7;
  --apple-surface: #ffffff;
  --apple-radius: 12px;
  --apple-radius-small: 8px;
  --apple-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
  --apple-shadow-elevated: 0 4px 20px rgba(0, 0, 0, 0.15);
}

.enum-select {
  width: 100%;
  font-family:
    -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;

  // 尺寸变化
  &--small {
    font-size: 14px;

    .mobile-trigger {
      min-height: 40px;
      padding: 8px 12px;
    }

    .enum-tab-item {
      min-height: 36px;
      padding: 6px 12px;
      font-size: 13px;
    }
  }

  &--default {
    font-size: 16px;
  }

  &--large {
    font-size: 18px;

    .mobile-trigger {
      min-height: 56px;
      padding: 16px 20px;
    }

    .enum-tab-item {
      min-height: 48px;
      padding: 12px 20px;
      font-size: 17px;
    }
  }

  &--disabled {
    opacity: 0.6;
    pointer-events: none;
  }

  // 单选按钮样式
  .enum-radio-group {
    .enum-radio-item {
      margin-bottom: 16px;

      .radio-content {
        display: flex;
        flex-direction: column;
        gap: 4px;

        .radio-label {
          font-size: 16px;
          font-weight: 500;
          color: #1d1d1f;
          line-height: 1.4;
        }

        .radio-tooltip {
          font-size: 14px;
          color: var(--apple-gray);
          line-height: 1.3;
        }
      }
    }
  }

  // Tab 样式
  .enum-tabs {
    display: flex;
    flex-wrap: wrap;
    gap: 12px;
    padding: 4px;

    .enum-tab-item {
      display: flex;
      align-items: center;
      gap: 6px;
      padding: 12px 20px;
      font-size: 16px;
      font-weight: 500;
      border-radius: var(--apple-radius);
      background-color: var(--apple-background);
      color: var(--apple-gray-dark);
      transition: all 0.2s cubic-bezier(0.4, 0, 0.2, 1);
      min-height: 44px;
      box-sizing: border-box;
      cursor: pointer;
      user-select: none;
      border: 1px solid transparent;

      .tab-label {
        line-height: 1.2;
      }

      .tab-info-icon {
        color: var(--apple-gray);
        transition: color 0.2s ease;
      }

      &:hover:not(.enum-tab-item--disabled) {
        background-color: #e5e5ea;
        transform: translateY(-1px);
      }

      &:active:not(.enum-tab-item--disabled) {
        transform: translateY(0) scale(0.98);
        background-color: #d1d1d6;
      }

      &--active {
        background-color: var(--apple-blue);
        color: white;
        border-color: var(--apple-blue);
        box-shadow: var(--apple-shadow);

        .tab-info-icon {
          color: rgba(255, 255, 255, 0.8);
        }

        &:hover {
          background-color: var(--apple-blue-light);
        }
      }

      &--disabled {
        opacity: 0.4;
        pointer-events: none;
        cursor: not-allowed;
      }
    }
  }

  // 移动端样式
  .enum-mobile {
    .mobile-trigger {
      display: flex;
      align-items: center;
      justify-content: space-between;
      padding: 14px 16px;
      background-color: var(--apple-surface);
      border: 1px solid var(--apple-gray-light);
      border-radius: var(--apple-radius);
      min-height: 48px;
      box-sizing: border-box;
      cursor: pointer;
      transition: all 0.2s cubic-bezier(0.4, 0, 0.2, 1);
      user-select: none;

      .mobile-label {
        font-size: 16px;
        color: #1d1d1f;
        flex: 1;
        line-height: 1.4;
        font-weight: 400;

        &--placeholder {
          color: var(--apple-gray);
        }
      }

      .mobile-arrow {
        color: var(--apple-gray);
        transition: all 0.2s cubic-bezier(0.4, 0, 0.2, 1);
        margin-left: 8px;

        &--active {
          transform: rotate(180deg);
          color: var(--apple-blue);
        }
      }

      &:hover {
        border-color: var(--apple-blue);
        box-shadow: 0 0 0 3px rgba(0, 122, 255, 0.1);
      }

      &--active {
        border-color: var(--apple-blue);
        box-shadow: 0 0 0 3px rgba(0, 122, 255, 0.15);
      }
    }
  }
}

// 弹窗样式
.mobile-picker-popup {
  .picker-container {
    background-color: var(--apple-surface);
    border-radius: var(--apple-radius) var(--apple-radius) 0 0;
    overflow: hidden;
    box-shadow: var(--apple-shadow-elevated);
  }

  .picker-header {
    background-color: var(--apple-surface);
    border-bottom: 1px solid var(--apple-gray-light);

    .picker-header-content {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 16px 20px;
    }

    .picker-title {
      font-size: 17px;
      font-weight: 600;
      color: #1d1d1f;
    }

    .picker-done-btn {
      background-color: var(--apple-blue);
      border-radius: var(--apple-radius-small);
      padding: 8px 16px;
      font-weight: 600;
      border: none;
      color: white;

      &:active {
        background-color: var(--apple-blue-dark);
      }
    }
  }

  .picker-search {
    padding: 16px 20px;
    background-color: var(--apple-background);
    border-bottom: 1px solid var(--apple-gray-light);

    .search-input-wrapper {
      position: relative;
      display: flex;
      align-items: center;
      background-color: var(--apple-surface);
      border-radius: var(--apple-radius-small);
      border: 1px solid var(--apple-gray-light);
      padding: 8px 12px;
      transition: all 0.2s ease;

      &:focus-within {
        border-color: var(--apple-blue);
        box-shadow: 0 0 0 3px rgba(0, 122, 255, 0.1);
      }

      .search-icon {
        color: var(--apple-gray);
        margin-right: 8px;
      }

      .search-input {
        flex: 1;
        border: none;
        outline: none;
        font-size: 16px;
        color: #1d1d1f;
        background: transparent;

        &::placeholder {
          color: var(--apple-gray);
        }
      }

      .search-clear {
        color: var(--apple-gray);
        cursor: pointer;
        padding: 4px;
        margin-left: 8px;

        &:hover {
          color: var(--apple-gray-dark);
        }
      }
    }
  }

  .picker-content {
    max-height: 50vh;
    background-color: var(--apple-surface);

    .picker-item {
      display: flex;
      align-items: center;
      justify-content: space-between;
      padding: 16px 20px;
      border-bottom: 1px solid rgba(0, 0, 0, 0.05);
      transition: all 0.2s cubic-bezier(0.4, 0, 0.2, 1);
      cursor: pointer;
      user-select: none;

      .picker-item-content {
        flex: 1;
        display: flex;
        flex-direction: column;
        gap: 4px;

        .picker-item-text {
          font-size: 16px;
          color: #1d1d1f;
          font-weight: 400;
          line-height: 1.4;
        }

        .picker-item-tooltip {
          font-size: 14px;
          color: var(--apple-gray);
          line-height: 1.3;
        }
      }

      .picker-item-check {
        color: var(--apple-blue);
        margin-left: 12px;
      }

      &:hover:not(.picker-item--disabled) {
        background-color: rgba(0, 122, 255, 0.04);
      }

      &:active:not(.picker-item--disabled) {
        background-color: rgba(0, 122, 255, 0.08);
        transform: scale(0.98);
      }

      &--selected {
        background-color: rgba(0, 122, 255, 0.08);

        .picker-item-text {
          color: var(--apple-blue);
          font-weight: 500;
        }
      }

      &--disabled {
        opacity: 0.4;
        pointer-events: none;
        cursor: not-allowed;

        .picker-item-text {
          color: var(--apple-gray);
        }
      }
    }

    .picker-empty {
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      padding: 60px 20px;

      .empty-icon {
        color: var(--apple-gray-light);
        margin-bottom: 16px;
      }

      .empty-text {
        font-size: 16px;
        color: var(--apple-gray);
        text-align: center;
      }
    }
  }
}

// 深色模式适配
@media (prefers-color-scheme: dark) {
  :root {
    --apple-background: #000000;
    --apple-surface: #1c1c1e;
    --apple-gray: #8e8e93;
    --apple-gray-light: #48484a;
    --apple-gray-dark: #ebebf5;
  }
}

// 响应式断点
@media (max-width: 375px) {
  .enum-select {
    .enum-tabs {
      gap: 8px;

      .enum-tab-item {
        padding: 10px 16px;
        font-size: 15px;
      }
    }

    .mobile-trigger {
      padding: 12px 14px;
    }
  }
}
</style>
